<template>
  <div id="bodypage">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/homePage' }"><span id="mainpage">主页</span></el-breadcrumb-item>
      <el-breadcrumb-item>绒质信息</el-breadcrumb-item>
      <el-breadcrumb-item><span>数据分析</span></el-breadcrumb-item>
    </el-breadcrumb>
    <h2 style="text-align: center; font-size: 2.1875rem; margin-top: 1.25rem; margin-bottom: 2.5rem; color: #000;">
      羊绒细度信息分析图</h2>
    <div style="text-align: center; width: 68.75rem; margin: auto;">
      <el-form :model="tableData" :inline="true" style="display: flex; justify-content: space-around;">
        <div style="display: inline-block;">
          <el-form-item label="直径搜索区间 :" style="margin-right: 0;">
            <el-input style="width: 100px;" type="text" placeholder="最小值" autocomplete="off"
              v-model="tableData.diameterMin">
            </el-input>
          </el-form-item>
          <span style="margin: 0 5px; height: 40px; display: inline-block; line-height: 40px;">--</span>
          <el-form-item>
            <el-input style="width: 100px;" type="text" placeholder="最大值" autocomplete="off"
              v-model="tableData.diameterMax">
            </el-input>
          </el-form-item>
        </div>
        <div style="display: inline-block;">
          <el-form-item label="分度 :" style="margin-right: 0;">
            <el-input style="width: 100px;" type="text" placeholder="最小为0.01" autocomplete="off"
              v-model="tableData.graduation">
            </el-input>
          </el-form-item>
        </div>
        <div style="display: inline-block;">
          <el-form-item label="年份选择 :" style="margin-right: 0;">
            <el-select style="width: 100px;" v-model="yearValue" clearable placeholder="请选择年份"
              @change="getAllCashmereInfo">
              <el-option v-for="item in yearOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <button id="oneSubmit" style="margin-left: 1.25rem" @click.prevent="getAllCashmereInfo">
            <i class="el-icon-search" style="color: #fff;">&nbsp;搜索</i>
          </button>
        </div>
      </el-form>
    </div>
    <div ref="barCharts" style="margin: auto;"></div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        tableData: {
          diameterMax: 20,
          diameterMin: 10,
          graduation: 1
        },
        yearOptions: [],
        yearValue: '',
        allGoatDataCount: [],
        barChart: null, // 存放初始化的echarts实例
        Timer: null, // 定时器
      }
    },
    mounted() {
      this.getAllYears()
      this.getAllCashmereInfo()
    },
    methods: {
      // 为选择器获取从2017年到今年的数据选项
      getAllYears() {
        let thisYear = new Date().getFullYear()
        const tempYearObj = {}
        for (let yearIndex = 2017; yearIndex <= thisYear; yearIndex++) {
          tempYearObj.label = String(yearIndex)
          tempYearObj.value = String(yearIndex)
          this.yearOptions.push(JSON.parse(JSON.stringify(tempYearObj)))
        }
        this.yearValue = String(thisYear) // 默认为当年
      },
      // 获取数据
      async getAllCashmereInfo(diameterMin, diameterMax) {
        // 如果传参就使用参数
        if (diameterMin && diameterMax) {
          this.tableData.diameterMin = diameterMin
          this.tableData.diameterMax = diameterMax
        }
        if (Number((this.tableData.diameterMax - this.tableData.diameterMin).toFixed(2)) < this.tableData.graduation) {
          console.log(Number((this.tableData.diameterMax - this.tableData.diameterMin).toFixed(2)));
          return this.$message({
            message: "搜索区间必须大于分度",
            center: true,
            type: 'error',
            duration: 3000
          });
        }
        if (this.tableData.graduation < 0.01) {
          return this.$message({
            message: "分度最小为0.01",
            center: true,
            type: 'error',
            duration: 3000
          });
        }
        let { data } = await this.$axios({
          method: 'post',
          url: '/summary/cashmere',
          data: {
            diameterMax: this.tableData.diameterMax,   //直径最大值
            diameterMin: this.tableData.diameterMin, //直径最小值
            //上面两个参数为默认值
            //下面的参数两两成对，为选项。后端拓展功能，根据是否有需求，去选择是否访问
            diameter_differenceMax: '', //直径标准差最大值
            diameter_differenceMin: '', //直径标准差最小值
            lengthMax: '',     //长度最大值
            lengthMin: '',      //长度最小值
            length_lengthMax: '',  //长度标准差最大值
            length_lengthMin: '',  //长度标准差最小值
            length_codefficientMax: '',     //长度变异系数最大值
            length_codefficientMin: '',       //长度变异系数最小值
            //年度默认当前年，只允许有四位数
            year: this.yearValue,                          //年度
          }
        })
        //如果查询成功
        // 筛选出所查找年份的羊只
        // let goatData = data.date.result2.filter(obj => {
        //   return Number(obj.MEASUREMENT_DATE.slice(0, 4)) == Number(this.yearValue)
        // })
        if (this.yearValue == '') this.yearValue = new Date().getFullYear() // 如果选择的年份为
        let goatData
        if (data.msg == '无数据') {
          goatData = []
        } else {
          goatData = data.data.result;
        }
        if (data.code === 0) {
          this.$message({
            message: goatData ? '共有' + data.data.length + '条数据' : '共有0条数据',
            center: true,
            type: 'success',
            duration: 3000
          });
        } else {
          //查询失败
          this.handleData(goatData)
          return this.$message({
            type: 'error',
            center: true,
            message: data.msg,
            duration: 1500
          })
        }
        this.handleData(goatData)
      },
      // 为图表处理获取的数据
      handleData(data) {
        // let tempData = 0
        // if (!data) { // 如果数据不为空
        //   tempData = data[0].DIAMETER
        // }
        // 筛选出直径最大值
        // for (let index = 1; index < data.length; index++) {
        //   if (tempData < data[index].DIAMETER) tempData = data[index].DIAMETER
        // }
        // let diameterMaxValue = tempData
        const categoryData = [];
        const valueData = [];
        // let iSub1; // 保存i的上一个值
        // let lastIValue; // 保存最终的i值
        // for (let i = Number(this.tableData.diameterMin); i <= Number(this.tableData.diameterMax); iSub1 = i, i = Number((i + Number(this.tableData.graduation)).toFixed(2))) {
        //   if (i != this.tableData.diameterMin) {
        //     categoryData.push(Number(iSub1) + '--' + i); // 添加横坐标数据,分度为graduation
        //     let $$this = this
        //     const tempArr = data.filter(obj => {
        //       return i >= $$this.tableData.diameterMax ? (obj.DIAMETER >= Number(iSub1) && obj.DIAMETER <= i) : (obj.DIAMETER >= Number(iSub1) && obj.DIAMETER < i)
        //     })
        //     valueData.push(tempArr.length); // 将对应羊只数放入纵坐标
        //     lastIValue = i;
        //   }
        // }
        // // 如果最后一个区间小于分度
        // if (lastIValue < Number(this.tableData.diameterMax)) {
        //   categoryData.push(lastIValue + '--' + this.tableData.diameterMax);
        //   const tempArr = data.filter(obj => {
        //     return obj.DIAMETER >= lastIValue && obj.DIAMETER <= this.tableData.diameterMax
        //   })
        //   valueData.push(tempArr.length); // 将对应羊只数放入纵坐标
        // }
        for (let i = Number(this.tableData.diameterMin); i <= Number(this.tableData.diameterMax); i = Number((i + Number(this.tableData.graduation)).toFixed(2))) {
          let iPlus1 = Number((i + Number(this.tableData.graduation)).toFixed(2))
          if(iPlus1 > this.tableData.diameterMax) iPlus1 = this.tableData.diameterMax;
          if(i == this.tableData.diameterMax) break;
          categoryData.push(i + '--' + iPlus1); // 添加横坐标数据,分度为graduation
          const tempArr = data.filter(obj => {
            return iPlus1 == this.tableData.diameterMax ? obj.DIAMETER >= i && obj.DIAMETER <= iPlus1 : obj.DIAMETER >= i && obj.DIAMETER < iPlus1
          })
          valueData.push(tempArr.length); // 将对应羊只数放入纵坐标
        }
        this.barCharts(categoryData, valueData, data)
      },
      // 创建图表实例
      barCharts(categoryData, valueData, data) {
        this.$refs.barCharts.style.width = 68.75 + 'rem'
        this.$refs.barCharts.style.height = 28.125 + 'rem'
        if (!this.barChart) { // 如果没有初始化
          this.barChart = this.$echarts.init(this.$refs.barCharts)
          let $this = this
          // 绑定单击事件
          $this.barChart.getZr().on('click', function (params) {
            let point = [params.offsetX, params.offsetY];
            if ($this.barChart.containPixel('grid', point)) {
              let xIndex = $this.barChart.convertFromPixel({ seriesIndex: 0 },
                point)[0];
              let op = $this.barChart.getOption();
              let name = op.xAxis[0].data[xIndex];
              clearTimeout($this.Timer);
              $this.Timer = setTimeout(function () {
                let diameterInterval = Number(($this.tableData.diameterMax - $this.tableData.diameterMin).toFixed(2));
                // console.log(name);
                const clickValueArr = name.split("--");
                // console.log(clickValueArr);
                // 如果区间大于0.05则点击将区间放大10倍
                let clickValueMin = Number(clickValueArr[0]);
                let clickValueMax = Number(clickValueArr[1]);
                let median = Number(((clickValueMax + clickValueMin) / 2).toFixed(3))
                // console.log("median is" + median);
                let enlargeDiameterMin = Number((median - diameterInterval / 20).toFixed(3));
                let enlargeDiameterMax = Number((median + diameterInterval / 20).toFixed(3));
                // console.log("min and max is" + enlargeDiameterMin + "and" + enlargeDiameterMax);
                if (Number((enlargeDiameterMax - enlargeDiameterMin).toFixed(2)) < $this.tableData.graduation) {
                  return $this.$message({
                    message: "已最大!!!",
                    center: true,
                    type: 'error',
                    duration: 2000
                  });
                }
                if (diameterInterval > 0.01) $this.getAllCashmereInfo(enlargeDiameterMin, enlargeDiameterMax)
              }, 500);
            }
          })
          // 绑定双击事件
          this.barChart.getZr().on('dblclick', function (params) {
            clearTimeout($this.Timer); // 如果执行双击事件则不执行单击事件
            let point = [params.offsetX, params.offsetY];
            if ($this.barChart.containPixel('grid', point)) {
              let xIndex = $this.barChart.convertFromPixel({ seriesIndex: 0 },
                point)[0];
              let op = $this.barChart.getOption();
              let name = op.xAxis[0].data[xIndex];
              $this.$store.commit('diameterInterval', name)
              $this.$router.push("/finenessDete")
            }
          })
        }
        let option = {
          title: {
            text: '共' + data.length + '条数据',
            left: '10%'
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: false
              },
              dataView: {
                readOnly: false
              },
              magicType: {
                type: ["line", "bar"]
              },
              restore: {},
              saveAsImage: {
                pixelRatio: 2
              },
            },
            right: '10%'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
          },
          grid: {
            bottom: 90,
            containLabel: true
          },
          dataZoom: [
            {
              type: 'inside'
            },
            {
              type: 'slider'
            }
          ],
          xAxis: {
            data: categoryData,
            silent: false,
            splitLine: {
              show: false
            },
            splitArea: {
              show: false
            },
            axisLabel: {
              // interval: 0,
              // hideOverlap: true
              // rotate: 90
            },
            // axisTick: {
            //   alignWithLabel: true
            // }
          },
          yAxis: {
            splitArea: {
              show: false
            }
          },
          series: [
            {
              type: 'bar',
              data: valueData,
              // Set `large` for large data amount
              large: true
            }
          ]
        };
        // function generateData(count, vm) {
        //   function next(idx) {

        //   }
        //   const categoryData = [];
        //   const valueData = [];
        //   for (let i = 0; i < count; i = Number((i + 0.01).toFixed(2))) {
        //     categoryData.push(i);
        //     if ()
        //       valueData.push(next(i).toFixed(2));
        //     time += 1000;
        //   }
        //   return {
        //     categoryData: categoryData,
        //     valueData: valueData
        //   };
        // }
        this.barChart.setOption(option)
      }
    },
  }

</script>
<style Lang="less" scoped>
  * {
    color: #4b9100;
  }

  #oneSubmit {
    background-color: transparent;
    position: relative;
    width: 110px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    text-decoration: none;
    text-transform: uppercase;
    background-image: linear-gradient(to right, #69ff97, #00e4ff, #69ff97);
    border: none;
    border-radius: 30px;
    cursor: pointer;
    background-size: 400%;
    z-index: 1;
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
    margin-left: 3%;
  }

  #oneSubmit::before {
    content: "";
    position: absolute;
    top: -5px;
    bottom: -5px;
    left: -5px;
    right: -5px;
    border-radius: 30px;
    background-image: linear-gradient(to right, #69ff97, #00e4ff, #69ff97);
    background-size: 400%;
    z-index: -1;
  }

  #oneSubmit:hover {
    animation: sun 10s infinite;
  }

  #oneSubmit:hover::before {
    animation: sun 10s infinite;
  }

  @keyframes sun {
    100% {
      background-position: -400% 0;
    }
  }
</style>